package com.spic.business.xfalarm.runner;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.spic.business.alarm.utils.DateTimeUtil;
import com.spic.business.xfalarm.service.IAlarmInfoDateService;
import com.spic.business.xfalarm.service.IDeviceInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.*;

@Service
@EnableScheduling
public class SyncProcessor
{
    private static final Logger log = LoggerFactory.getLogger(SyncProcessor.class);

    @Value("${corePoolSize}")
    private Integer corePoolSize;

    @Value("${maxPoolSzie}")
    private Integer maxPoolSzie;

    @Autowired
    private IAlarmInfoDateService alarmInfoDateService;
    @Autowired
    private IDeviceInfoService deviceInfoService;


    ThreadFactory namedThreadFactory = (new ThreadFactoryBuilder()).setNameFormat("schedule-pool-%d").build();

    ExecutorService singleThreadPool;

    private void initThreadPool() {
        this.singleThreadPool = new ThreadPoolExecutor(this.corePoolSize.intValue(), this.maxPoolSzie.intValue(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), this.namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    }
    @Scheduled(cron = "${schedule.cron}")
    public void sync() {
        if (this.singleThreadPool == null)
            initThreadPool();

        this.singleThreadPool.execute(new Runnable()
        {
            @Override
            public void run()
            {
                initData();
            }
        });
    }
    public void initData() {
        log.info("消防告警数据同步至ods开始******************************");
        boolean monthBeginDate = DateTimeUtil.isMonthBeginDate();
        if(monthBeginDate){
            String lastDate = DateTimeUtil.getLastDate(new Date());
            alarmInfoDateService.alarmInfoQueryList(lastDate);
        }
        String yyyyMMdd = DateTimeUtil.dateToStr(new Date(), "yyyyMM");
        alarmInfoDateService.alarmInfoQueryList(yyyyMMdd);
        deviceInfoService.queryDeviceInfoList();
        log.info("消防告警数据同步至ods结束******************************");
    }
}

